package com.app.web.merchant;

import com.app.utils.base.j2se.Common;
import com.app.utils.base.j2se.Convert;
import com.app.utils.base.j2se.JsonUtil;
import com.app.utils.base.j2se.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description
 * Created by 王伟
 * Date create on 11:49 2019/11/26.
 */
@Service
public class MerchantManager {
    @Autowired
    private MerchantDao merchantDao;

    private static Map<Integer,Merchant> merchants = new HashMap<>();
    private static Map<String,Integer> rateMap = new HashMap<>();
    private static Map<String,Integer> rateChannelMap = new HashMap<>();

    @PostConstruct
    void init(){
        loadMerchants();
        new Thread(()->{
            try {
                while (true){
                    Thread.sleep(60000);
                    loadMerchants();
                }
            } catch (Exception e) {
                Logger.error("加载商家信息、类目分佣比例失败",e);
            }
        }).start();
    }

    private void loadMerchants(){
        Map<String,Object> param = new HashMap<>();
        param.put("sort", "ASC");
        /* 查询所有商家 */
        List<Merchant> merchantList = merchantDao.merchantList(param);
        if(Common.isEmpty(merchantList) || merchantList.size() == 0)return;
        /* 组装商家信息 */
        merchants = merchantList.stream().collect(Collectors.toMap(Merchant::getId,Function.identity()));
    }

    public static Map<String,Object> getMerchantById(int id){
        return JsonUtil.beanToMap(merchants.get(id));
    }

    /* 商家列表搜索查询 */
    public static List<Merchant> getMerchantList(String name, int is_recommend, int page){
        /* 将数据转换为流 */
        Stream<Map.Entry<Integer, Merchant>> stream = merchants.entrySet().stream();
        /* 严选 */
        if(is_recommend!=0)stream = stream.filter(x->Convert.objToInt(x.getValue().getIsRecommend())==is_recommend);
        /* 根据商家名称模糊查询 */
        if(Common.isNotEmpty(name))stream = stream.filter(x->Convert.objToStr(x.getValue().getName()).contains(name));
        /* 提取流信息为List */
        List<Merchant> data = stream.map(Map.Entry::getValue).collect(Collectors.toList());
        /* 分页返回 */
        return page>0?data.stream().skip((page-1)*20).limit(20).collect(Collectors.toList()):data;
    }

    /* 获取商家类目比例 */
    public static int getRate(int hosId,int catId){
        return Common.isNotEmpty(rateMap)?Convert.objToInt(rateMap.get(String.format("%s_%s",hosId,catId))):0;
    }

    /* 获取商家类目比例 */
    public static int getChannelRate(int hosId,int catId){
        return Common.isNotEmpty(rateChannelMap)?Convert.objToInt(rateChannelMap.get(String.format("%s_%s",hosId,catId))):0;
    }

}
